var light_flag;                                     //将灯的开关状态设置为全局变量
$(function () {
    var aid = "8412";                                //序列号
    var key = "8412";                               //密钥
    var myLightMac = "00:12:4B:00:1A:BE:7B:9B";                //传感器的MAC地址
    var light = new WSNRTConnect(aid, key);        //创建数据连接服务对象
    light.setServerAddr("192.168.12.110:28080");					//服务器端口
    light.connect();
    light.onConnect = function () {                                //连接成功回调函数H
        light.sendMessage(myLightMac, "{D1=?}");            //向传感器发送数据
        $("#LightConnectState").text("警报灯连接成功！");
    };

    light.onConnectLost = function () {                            //数据服务掉线回调函数
        $("#LightConnectState").text("警报灯掉线！");
    };

    light.onmessageArrive = function (mac, dat) {                   //消息处理回调函数
        if (mac == myLightMac) {                               //判断传感器Mac地址
            if (dat[0] == '{' && dat[dat.length - 1] == '}') {  //判断字符串首尾是否为{}
                dat = dat.substr(1, dat.length - 2);            //截取{}内的字符串
                var its = dat.split(',');                       //以‘,’来分割字符串
                for (var x in its) {
                    var t = its[x].split('=');                //以‘=’来分割字符串
                    if (t.length != 2) continue;
                    if (t[0] == "D1") {                         //判断参数D1
                        edge = parseInt(t[1]);
                        if ((edge & 0x08) != 0x08) {
                            $("#light_state").text("灯已关闭");
                            $("#light_switch").text("打开警报灯");
                            light_flag = 0;
                        } else {
                            $("#light_state").text("灯已打开");
                            $("#light_switch").text("关闭警报灯");
                            light_flag = 1;
                        }
                    }
                }
            }
        }
    }


    //警报灯（继电器四号灯）开关按钮
    $("#light_switch").click(function () {                         //第四路继电器按钮
        if (light_flag) {
            light.sendMessage(myLightMac, "{CD1=8,D1=?}");       //关闭第四路继电器
        } else {
            light.sendMessage(myLightMac, "{OD1=8,D1=?}");       //打开第四路继电器
        }
    });
});